package com.igorkundovic.guitarstab.components;

import org.apache.tapestry5.*;
import org.apache.tapestry5.annotations.*;
import org.apache.tapestry5.ioc.annotations.*;
import org.apache.tapestry5.services.RequestGlobals;
import org.apache.tapestry5.BindingConstants;

import com.igorkundovic.guitarstab.User;
import com.igorkundovic.guitarstab.pages.Index;
import com.igorkundovic.guitarstab.pages.Login;
import com.igorkundovic.guitarstab.pages.Register;
import com.igorkundovic.guitarstab.pages.Welcome;
import com.igorkundovic.guitarstab.service.CommentService;
import com.igorkundovic.guitarstab.service.TabService;
import com.igorkundovic.guitarstab.service.UserService;



/**
 * Layout component for pages of application guitartabs.
 */
@IncludeStylesheet("context:layout/layout.css")
public class Layout
{
    /** The page title, for the <title> element and the <h1> element. */
    @Property
    @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
    private String title;

    @Inject
	private RequestGlobals requestGlobals;
	
	@ApplicationState
	private User user;
	private boolean userExists;
	
	@Inject
	private UserService userservice;
	
	@Inject
	private TabService tabservice;
	
	@Inject
	private CommentService commentservice;
	
	
	public Object onActivate(){
		
		if (userExists) {
			return null;
		}
		return Login.class;
		
	}
	
	@OnEvent(component="logout")
	Object logOut(){
		
		
		
		requestGlobals.getHTTPServletRequest().getSession().invalidate();
		
		return Index.class;
	}
	
	@OnEvent(component="deleteuser")
	public Object delete(){
		boolean deleted=tabservice.deleteTab(user);
		if(deleted){
			commentservice.deleteComment(user);
			userservice.deleteUser(user);
			return Welcome.class;
		}
		boolean deleted2=commentservice.deleteComment(user);
		if(deleted2){
			tabservice.deleteTab(user);
			userservice.deleteUser(user);
			return Welcome.class;
		}
		boolean deleted3=userservice.deleteUser(user);
		if(deleted3){
			return Welcome.class;
		}
		else{
			return this;
		}
	}
	
	public boolean isUserExists() {
		return userExists;
	}
    @Property
    private String pageName;

    @Property
    @Parameter(defaultPrefix = BindingConstants.LITERAL)
    private String sidebarTitle;

    @Property
    @Parameter(defaultPrefix = BindingConstants.LITERAL)
    private Block sidebar;

    @Inject
    private ComponentResources resources;

    public String getClassForPageName()
    {
      return resources.getPageName().equalsIgnoreCase(pageName)
             ? "current_page_item"
             : null;
    }

    public String[] getPageNames()
    {
      return new String[] { "Index", "About", "Contact" };
    }
}
